package fr.xebia.monitoring.appender;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import fr.xebia.monitoring.MonitoringException;
import fr.xebia.monitoring.beans.AggregatedMeasures;
import fr.xebia.monitoring.beans.Measure;
import fr.xebia.monitoring.config.MeasureType;

public class FileAppender extends AbstractMeasureAppender {

	private boolean append = true;
	private String file;

	@Override
	public void run() {
		Writer writer = null;
		try {
			if (append) {
				writer = new BufferedWriter(new FileWriter(file, true));
			} else {
				writer = new BufferedWriter(new FileWriter(file));
			}
			if (getMeasureType().equals(MeasureType.AGGREGATED)) {
				logger.debug("Appending aggregated measures");
				AggregatedMeasures agregatedMeasures = getAggregatedMeasures();
				getFormater().format(agregatedMeasures, writer);
			} else {
				logger.debug("Appending raw measures");
				Measure[] measures = getMeasures();
				getFormater().format(measures, writer);
			}
		} catch (IOException e) {
			logger.error("Can't write output file: "+file+", appender will stop", e);
			throw new MonitoringException("Can't write output file: "+file, e);
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					logger.warn("Can't close the file: " + file, e);
				}
			}
		}
	}

	protected void setAppend(boolean append) {
		this.append = append;
	}

	protected void setFile(String file) {
		this.file = file;
	}
}
